//
//  BuleFuction.m
//  BlueToothDemo
//
//  Created by Jeamine on 16/1/21.
//  Copyright © 2016年 Jeamine. All rights reserved.
//

#import "BuleFuction.h"
#import "NSString+Hex.h"
#import "NSData+hex.h"
#import "RSA_C.h"
#import "AES128EBC_No_Padding_Unit.h"
#import "HemaConst.h"
#import "KLHelp.h"
#import "BBRSACryptor.h"
#import "GTMBase64.h"
#import "SSKeychain.h"

@implementation BuleFuction

#pragma mark - 获取aes密钥的第一包数据
+(void)doGetAESKeywith:(CBPeripheral *)peripheral and:(CBCharacteristic *)characteristic{
    Byte ucCommandSend[23];
    
    ucCommandSend[0]= 0xfa;
    ucCommandSend[1]= 0xfb;
    ucCommandSend[2]= 0x00;
    ucCommandSend[3]= 0x97;//数据长度
    ucCommandSend[4]= 0x50;
    ucCommandSend[5] = 0x50;
    for (int i = 6; i<22; i++)
    {
        ucCommandSend[i] = 0x00;
    }
    ucCommandSend[22] = 0x81;
    
    //包头
    NSMutableData *content=[NSMutableData dataWithBytes:ucCommandSend length:23];
    NSLog(@"第一包的包头长度：%zd",content.length);
    
    //打包rsa公钥
    SecKeyRef keyRef = [RSA_C addPublicKey:PUBLICKEYS];
    
    NSData *rsaModel = [self getPublicKeyBitsFromKey:keyRef];
   
    NSMutableData *rsaKeyData = [[NSMutableData alloc]initWithData:rsaModel];
    NSData *rsaSendData = [rsaKeyData subdataWithRange:NSMakeRange(7, 128)];
    
    [content appendData:rsaSendData];
    
    //cs累加和
    Byte CSSend[1];
    CSSend[0] = 0xe2;
    
    NSData *csSend = [rsaModel getCheckSum:rsaSendData];//获取到b1 求累加和的方法
    [content appendData:csSend];
    
    //结束符
    Byte endSend[8];
    endSend[0] = 0x16;
    
    endSend[1] = 0x00;
    endSend[2] = 0x00;
    endSend[3] = 0x00;
    endSend[4] = 0x00;
    endSend[5] = 0x00;
    endSend[6] = 0x00;
    endSend[7] = 0x00;
        
    NSData *endData = [NSData dataWithBytes:endSend length:8];
    [content appendData:endData];
    
    NSLog(@"发送的数据:%@",content);
    NSLog(@"发送的总数据长度：%zd",content.length);
    
    for (int i = 0; i<8; i++){
        NSData *sendData = [content subdataWithRange:NSMakeRange(i*20, 20)];
        NSString *responseFlag = [[NSUserDefaults standardUserDefaults] objectForKey:@"responseFlag"];
        if([responseFlag isEqualToString:@"1a"]){
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }else{
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
        }
    }
}

#pragma mark - 锁主钥匙开锁
+(void)doOpenLock:(NSData *)AesKey andPrigher:(CBPeripheral *)peripheral and:(CBCharacteristic*)characteristic withRSApublickeKey:(NSString *)rsaPublic{
    /***
     包头
     数据长度 0xb7
     控制码 0x82
     **/
    NSMutableData *openLockData = [[NSMutableData alloc]initWithCapacity:200];
    
    Byte ucCommandSend[23];
    ucCommandSend[0]= 0xfa;
    ucCommandSend[1]= 0xfb;
    ucCommandSend[2]= 0x00;
    ucCommandSend[3]= 0xe7;
    ucCommandSend[4]= 0x50;
    ucCommandSend[5] = 0x50;
    for (int i = 6; i<22; i++)
    {
        ucCommandSend[i] = 0x00;
    }
    ucCommandSend[22] = 0x82;
    NSData *headData = [NSData dataWithBytes:ucCommandSend length:23];
    [openLockData appendData:headData];
    /*********
     *用户名 numberData 12byte
     *本机时间 timeData 6byte YYMMDDHHMMSS
     ****/
    //当前用户绑定手机号
    NSString *nStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"userid"];
    NSString *numberStr = [KLHelp userIDToTwelveByteWithUserID:nStr];
    NSLog(@"发送的手机号:%@",numberStr);
    Byte nameUser[12];
    for (int i = 0; i<12;i++){
        NSString *byteStr = [numberStr substringWithRange:NSMakeRange(i, 1)];
        nameUser[i] = [byteStr strToByte:byteStr];
    }
    NSData *nameUserData = [NSData dataWithBytes:nameUser length:12];
    //本机当前时间
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYMMddHHmmss"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    
    NSData *timeData = [locationString convertHexStrToData:locationString];
    NSLog(@"本机当前时间:%@，时间字节长度:%zd",timeData,timeData.length);
    
    NSMutableData *firstData = [[NSMutableData alloc]initWithCapacity:18];
    [firstData appendData:nameUserData];
    [firstData appendData:timeData];
    NSLog(@"firstData:%@",firstData);
    
    NSMutableData *secondData = [[NSMutableData alloc]initWithCapacity:50];
    //权限码1bytes
    Byte limitCode[1];
    limitCode[0] = 0x00;
    //AESKey16bytes
    NSString *AESKeyCode = [KLHelp getUserSixTeenRandomAESKey];
    Byte AESKeyBytes[16];
    for (int i = 0; i<16;i++){
        NSString *byteStr = [AESKeyCode substringWithRange:NSMakeRange(i, 1)];
        AESKeyBytes[i] = [byteStr strToByte:byteStr];
    }
    NSData *AESKeyData = [NSData dataWithBytes:AESKeyBytes length:16];
    NSLog(@"limitData:%@",AESKeyData);
    //钥匙产生的时间6bytes
    NSDateFormatter *dateformatte=[[NSDateFormatter alloc] init];
    [dateformatte setDateFormat:@"YYMMddHHmmss"];
    NSString *locationStrin=[dateformatte stringFromDate:senddate];
    NSData *creatData = [locationStrin convertHexStrToData:locationStrin];
    NSLog(@"钥匙产生时间：%@",creatData);
    //命令序号2bytes
    Byte commondNumber[2];
    commondNumber[0] = 0x00;
    commondNumber[1] = 0x00;
    //协议新追加
    [secondData appendBytes:limitCode length:1];
    [secondData appendData:AESKeyData];
    [secondData appendData:creatData];
    [secondData appendData:[NSData dataWithBytes:commondNumber length:2]];
    //=================================================
    
    /***
     命令码 0xa1
     手机号
     起始时间
     终止时间 全是0
     ****/
    
    //命令码
    Byte sendCommand[1];
    sendCommand[0] = 0xa1;
    //起始时间
    NSString *starttime = @"000000000000";
    NSData *startData = [starttime convertHexStrToData:starttime];
    NSLog(@"钥匙起始时间：%@",startData);
    //终止时间
    NSString *endtimeStr =@"000000000000";
    NSData *endtimeData = [endtimeStr convertHexStrToData:endtimeStr];
    NSLog(@"钥匙结束时间：%@",endtimeData);
    
    [secondData appendData:[NSData dataWithBytes:sendCommand length:1]];//命令码
    [secondData appendData:nameUserData];//被授权用户的手机号
    [secondData appendData:startData];
    [secondData appendData:endtimeData];
    NSLog(@"secondData:%@",secondData);
   //RSA加密的数据包
    NSData *RSAData = [RSA_C encryptData:secondData publicKey:rsaPublic];
    NSLog(@"RSA加密后的数据:%@,长度:%zd",RSAData,RSAData.length);
    /******************************************************************************************/
    //锁主自定义AES包
    NSMutableData *newAesSecurit = [[NSMutableData alloc]initWithCapacity:38];
    //添加权限码
    [newAesSecurit appendBytes:limitCode length:1];
    //添加12个字节的设置用户(开锁指令为全0)
    [newAesSecurit appendData:startData];
    [newAesSecurit appendData:endtimeData];
    //添加命令码
    [newAesSecurit appendData:[NSData dataWithBytes:sendCommand length:1]];
    //添加当前用户
    [newAesSecurit appendData:nameUserData];
    //添加起始时间
    [newAesSecurit appendData:startData];
    //添加终止时间
    [newAesSecurit appendData:endtimeData];
    NSLog(@"aeskey:%@ 原文:%@",AESKeyCode,newAesSecurit);
    //对锁主自定义AES包加密
    NSData *newAesSecuritEncryption = [AES128EBC_No_Padding_Unit AES128Encrypt:newAesSecurit withAESKey:AESKeyData];
    NSLog(@"密文：%@",newAesSecuritEncryption);
    
    /**拼接18+128+48*/
    NSMutableData *mainData = [[NSMutableData alloc]init];
    [mainData appendData:firstData];
    [mainData appendData:RSAData];
    [mainData appendData:newAesSecuritEncryption];
    
    //最外层aes加密后的数据长度
    NSData *aesEncryData = [AES128EBC_No_Padding_Unit AES128Encrypt:mainData withAESKey:AesKey];
    NSLog(@"数据主体的长度:%zd",aesEncryData.length);
    [openLockData appendData:aesEncryData];
    
    //cs校验和
    NSData *csenddata = [aesEncryData getCheckSum:aesEncryData];
    [openLockData appendData:csenddata];
    NSLog(@"数据总长度是:%zd",openLockData.length+1);
    
    //结束符0x16
    Byte endCommand[8];
    endCommand[0] = 0x16;
    endCommand[1] = 0x00;
    endCommand[2] = 0x00;
    endCommand[3] = 0x00;
    endCommand[4] = 0x00;
    endCommand[5] = 0x00;
    endCommand[6] = 0x00;
    endCommand[7] = 0x00;
    
    NSData *endComData = [NSData dataWithBytes:endCommand length:8];
    [openLockData appendData:endComData];
    NSLog(@"开锁数据长度:%lu",(unsigned long)openLockData.length);
    for (int i = 0; i<openLockData.length/20; i++){
        NSData *sendData = [openLockData subdataWithRange:NSMakeRange(i*20, 20)];
        NSString *responseFlag = [[NSUserDefaults standardUserDefaults] objectForKey:@"responseFlag"];
        if([responseFlag isEqualToString:@"1a"]){
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }else{
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
        }
    }
}

#pragma mark - 打包子钥匙的数据包封装
+ (NSData *)packChildkeyToData:(NSString *)rsaPublicKey mobileStr:(NSString *)phone startTime:(NSString *)startTime endTime:(NSString *)endTime commondCode:(NSString *)commondCode userAESKey:(NSString *)AESKeyCode{
    NSMutableData *secondData = [[NSMutableData alloc]init];
    //权限码1bytes
    Byte limitCode[1];
    limitCode[0] = 0x00;
    //AESKey16bytes
    Byte AESKeyBytes[16];
    for (int i = 0; i<16;i++){
        NSString *byteStr = [AESKeyCode substringWithRange:NSMakeRange(i, 1)];
        AESKeyBytes[i] = [byteStr strToByte:byteStr];
    }
    NSData *AESKeyData = [NSData dataWithBytes:AESKeyBytes length:16];
    NSLog(@"limitData:%@",AESKeyData);
    //钥匙产生的时间6bytes和命令序号2bytes
    //钥匙产生时间即本机当前时间
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYMMddHHmmss"];
    NSString *creattime = [dateformatter stringFromDate:senddate];
    NSData *creatData = [creattime convertHexStrToData:creattime];
    NSLog(@"钥匙产生时间：%@",creatData);
    //命令序号
    commondCode = [NSString ToHex:commondCode.integerValue];
    if(commondCode.length < 3){
        commondCode = [NSString stringWithFormat:@"00%@",commondCode];
    }
    NSData *commondData = [commondCode convertHexStrToData:commondCode];
    NSLog(@"commondCode:%@ commondData:%@",commondCode,commondData);
    
    //协议新追加
    [secondData appendBytes:limitCode length:1];
    [secondData appendData:AESKeyData];
    [secondData appendData:creatData];
    [secondData appendData:commondData];
    //=================================================
    
    /***
     命令码 0xa1
     手机号
     起始时间
     终止时间
     ****/
    //命令码
    Byte sendCommand[1];
    sendCommand[0] = 0xa1;
    //要发送的对方的手机号
    NSString *numberStr = [NSString stringWithFormat:@"%@0",phone];
    NSLog(@"发送的手机号:%@",numberStr);
    Byte nameUser[12];
    for (int i = 0; i<12;i++ ){
        NSString *byteStr = [numberStr substringWithRange:NSMakeRange(i, 1)];
        nameUser[i] = [byteStr strToByte:byteStr];
    }
    NSData *nameUserData = [NSData dataWithBytes:nameUser length:12];
    //钥匙有效期的起始时间
    NSData *startData = [startTime convertHexStrToData:startTime];
    NSLog(@"钥匙起始时间：%@",startData);
    //钥匙有效期的终止时间
    NSData *endtimeData = [endTime convertHexStrToData:endTime];
    NSLog(@"钥匙结束时间：%@",endtimeData);
    
    [secondData appendData:[NSData dataWithBytes:sendCommand length:1]]; //命令码
    NSLog(@"sendCommand:%@",[NSData dataWithBytes:sendCommand length:1]);
    [secondData appendData:nameUserData]; //被授权用户的手机号
    [secondData appendData:startData];
    [secondData appendData:endtimeData];
    
    NSData *RSAData = [RSA_C encryptData:secondData publicKey:rsaPublicKey];
    NSLog(@"RSA加密后的数据长度:%zd",RSAData.length);
    
    return RSAData;
}

#pragma mark - 子钥匙开锁(需要加入用户aes密钥参数拼接)
+(void)accreditDoOpenLock:(NSData *)AesKey andPrigher:(CBPeripheral *)peripheral and:(CBCharacteristic *)characteristic withData:(NSData *)RSAData lastAESPackage:(NSData *)lastAESPackage{
    /***
     包头
     数据长度 0xe7
     控制码 0x82
     **/
    NSMutableData *openLockData = [[NSMutableData alloc]init];
    
    Byte ucCommandSend[23];
    ucCommandSend[0]= 0xfa;
    ucCommandSend[1]= 0xfb;
    ucCommandSend[2]= 0x00;
    ucCommandSend[3]= 0xe7;
    ucCommandSend[4]= 0x50;
    ucCommandSend[5] = 0x50;
    for (int i = 6; i<22; i++)
    {
        ucCommandSend[i] = 0x00;
    }
    ucCommandSend[22] = 0x82;
    NSData *headData = [NSData dataWithBytes:ucCommandSend length:23];
    [openLockData appendData:headData];
    /*********
     *用户名 numberData 12byte
     *本机时间 timeData 6byte YYMMDDHHMMSS
     ****/
    
    NSString *nStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"userid"];
    NSString *numberStr = [KLHelp userIDToTwelveByteWithUserID:nStr];
    Byte nameUser[12];
    for (int i = 0; i<12;i++ )
    {
        NSString *byteStr = [numberStr substringWithRange:NSMakeRange(i, 1)];
        nameUser[i] = [byteStr strToByte:byteStr];
        
    }
    NSData *nameUserData = [NSData dataWithBytes:nameUser length:12];
    NSLog(@"nameUSerData = %@ %zd",nameUserData,nameUserData.length);
    
    //本机时间
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYMMddHHmmss"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    NSLog(@"localtime :%@",locationString);
    
    NSData *timeData = [locationString convertHexStrToData:locationString];
    NSLog(@"timeData %@,length %zd",timeData,timeData.length);
    
    NSMutableData *firstData = [[NSMutableData alloc]init];
    [firstData appendData:nameUserData];
    [firstData appendData:timeData];
    NSLog(@"firstData = %@",firstData);
    
    /**
     拼接18+128+aesPackage
     */
    NSMutableData *mainData = [[NSMutableData alloc]init];
    [mainData appendData:firstData];
    [mainData appendData:RSAData];
    [mainData appendData:lastAESPackage];
    NSLog(@"lastAESPackage:%@",lastAESPackage);
    
    //aes
    NSData *aesEncryData = [AES128EBC_No_Padding_Unit AES128Encrypt:mainData withAESKey:AesKey];
    [openLockData appendData:aesEncryData];
    
    //cs
    NSData *csenddata = [aesEncryData getCheckSum:aesEncryData];
    [openLockData appendData:csenddata];
    //0x16
    Byte endCommand[8];
    endCommand[0] = 0x16;
    endCommand[1] = 0x00;
    endCommand[2] = 0x00;
    endCommand[3] = 0x00;
    endCommand[4] = 0x00;
    endCommand[5] = 0x00;
    endCommand[6] = 0x00;
    endCommand[7] = 0x00;
    
    NSData *endComData = [NSData dataWithBytes:endCommand length:8];
    [openLockData appendData:endComData];
    NSLog(@"openLockData:%@ 长度：%lu",openLockData,(unsigned long)openLockData.length);
    
    for (int i = 0; i<openLockData.length/20; i++)
    {
        NSData *sendData = [openLockData subdataWithRange:NSMakeRange(i*20, 20)];
        NSString *responseFlag = [[NSUserDefaults standardUserDefaults] objectForKey:@"responseFlag"];
        if([responseFlag isEqualToString:@"1a"]){
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }else{
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
        }
    }
}

#pragma mark - 锁主校时
+(void)checkoutTime:(NSData *)AesKey andPrigher:(CBPeripheral *)peripheral and:(CBCharacteristic *)characteristic withRSApublickeKey:(NSString *)rsaPublic{
    /***
     包头
     数据长度 0xb7
     控制码 0x82
     **/
    NSMutableData *openLockData = [[NSMutableData alloc]init];
    
    Byte ucCommandSend[23];
    
    ucCommandSend[0]= 0xfa;
    ucCommandSend[1]= 0xfb;
    ucCommandSend[2]= 0x00;
    ucCommandSend[3]= 0xe7;
    ucCommandSend[4]= 0x50;
    ucCommandSend[5] = 0x50;
    for (int i = 6; i<22; i++)
    {
        ucCommandSend[i] = 0x00;
    }
    ucCommandSend[22] = 0x82;
    NSData *headData = [NSData dataWithBytes:ucCommandSend length:23];
    [openLockData appendData:headData];
    /********
     *用户名 numberData 12byte
     *本机时间 timeData 6byte YYMMDDHHMMSS
     ********/
    //当前用户绑定手机号
    NSString *nStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"userid"];
    NSString *numberStr = [KLHelp userIDToTwelveByteWithUserID:nStr];
    NSLog(@"发送的手机号:%@",numberStr);
    Byte nameUser[12];
    for (int i = 0; i<12;i++ ){
        NSString *byteStr = [numberStr substringWithRange:NSMakeRange(i, 1)];
        nameUser[i] = [byteStr strToByte:byteStr];
    }
    NSData *nameUserData = [NSData dataWithBytes:nameUser length:12];
    
    //本机当前时间
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYMMddHHmmss"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    NSLog(@"本机当前时间:%@",locationString);
    
    NSData *timeData = [locationString convertHexStrToData:locationString];
    
    NSMutableData *firstData = [[NSMutableData alloc]init];
    [firstData appendData:nameUserData];
    [firstData appendData:timeData];
    
    NSMutableData *secondData = [[NSMutableData alloc]init];
    //权限码1bytes
    Byte limitCode[1];
    limitCode[0] = 0x00;
    //AESKey16bytes
    NSString *AESKeyCode = [KLHelp getUserSixTeenRandomAESKey];
    Byte AESKeyBytes[16];
    for (int i = 0; i<16;i++){
        NSString *byteStr = [AESKeyCode substringWithRange:NSMakeRange(i, 1)];
        AESKeyBytes[i] = [byteStr strToByte:byteStr];
    }
    NSData *AESKeyData = [NSData dataWithBytes:AESKeyBytes length:16];
    //钥匙产生的时间6bytes和命令序号2bytes
    //钥匙产生时间
    NSString *creattime = @"000000000000";
    NSData *creatData = [creattime convertHexStrToData:creattime];
    NSLog(@"产生时间：%@",creatData);
    //命令序号
    Byte commondNumber[2];
    commondNumber[0] = 0x00;
    commondNumber[1] = 0x00;
    //协议新追加
    [secondData appendBytes:limitCode length:1];
    [secondData appendData:AESKeyData];
    [secondData appendData:creatData];
    [secondData appendData:[NSData dataWithBytes:commondNumber length:2]];
    //=================================================
    
    /***
     命令码 0xc4
     手机号
     起始时间
     终止时间 全是0
     ****/
    
    //命令码
    Byte sendCommand[1];
    sendCommand[0] = 0xc4;
    //起始时间
    NSString *starttime = @"000000000000";
    NSData *startData = [starttime convertHexStrToData:starttime];
    NSLog(@"起始时间：%@",startData);
    //终止时间
    NSString *endtimeStr =@"000000000000";
    NSData *endtimeData = [endtimeStr convertHexStrToData:endtimeStr];
    NSLog(@"结束时间：%@",endtimeData);
    
    [secondData appendData:[NSData dataWithBytes:sendCommand length:1]];//命令码
    [secondData appendData:nameUserData];//被授权用户的手机号
    [secondData appendData:startData];
    [secondData appendData:endtimeData];
    
    
    NSData *RSAData = [RSA_C encryptData:secondData publicKey:rsaPublic];
    NSLog(@"RSA加密后的数据长度:%zd",RSAData.length);
    /******************************************************************************************/
    //锁主自定义AES包
    NSMutableData *newAesSecurit = [[NSMutableData alloc]initWithCapacity:38];
    //添加权限码
    [newAesSecurit appendBytes:limitCode length:1];
    //添加12个字节的设置用户(开锁指令为全0)
    [newAesSecurit appendData:startData];
    [newAesSecurit appendData:endtimeData];
    //添加命令码
    [newAesSecurit appendData:[NSData dataWithBytes:sendCommand length:1]];
    //添加当前用户
    [newAesSecurit appendData:nameUserData];
    //添加起始时间
    [newAesSecurit appendData:startData];
    //添加终止时间
    [newAesSecurit appendData:endtimeData];
    //对锁主自定义AES包加密
    NSData *newAesSecuritEncryption = [AES128EBC_No_Padding_Unit AES128Encrypt:newAesSecurit withAESKey:AESKeyData];
    /**
     拼接18+128+48
     */
    NSMutableData *mainData = [[NSMutableData alloc]init];
    [mainData appendData:firstData];
    [mainData appendData:RSAData];
    [mainData appendData:newAesSecuritEncryption];
    
    //aes
    NSData *aesEncryData = [AES128EBC_No_Padding_Unit AES128Encrypt:mainData withAESKey:AesKey];
    NSLog(@"数据主体的长度:%zd",aesEncryData.length);
    
    [openLockData appendData:aesEncryData];
    
    //cs
    NSData *csenddata = [aesEncryData getCheckSum:aesEncryData];
    [openLockData appendData:csenddata];
    
    //0x16
    Byte endCommand[8];
    endCommand[0] = 0x16;
    endCommand[1] = 0x00;
    endCommand[2] = 0x00;
    endCommand[3] = 0x00;
    endCommand[4] = 0x00;
    endCommand[5] = 0x00;
    endCommand[6] = 0x00;
    endCommand[7] = 0x00;
    
    NSData *endComData = [NSData dataWithBytes:endCommand length:8];
    [openLockData appendData:endComData];
    NSLog(@"校时数据长度:%lu",(unsigned long)openLockData.length);
    for (int i = 0; i<openLockData.length/20; i++){
        NSData *sendData = [openLockData subdataWithRange:NSMakeRange(i*20, 20)];
        NSString *responseFlag = [[NSUserDefaults standardUserDefaults] objectForKey:@"responseFlag"];
        if([responseFlag isEqualToString:@"1a"]){
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }else{
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
        }
    }
}

#pragma mark - 打包校时命令包
+(NSData *)packageCheckTimeToDataWithRsaPublickey:(NSString *)rsaPublicKey userAESKey:(NSString *)AESKeyCode{
    NSMutableData *secondData = [[NSMutableData alloc]init];
    //权限码1bytes
    Byte limitCode[1];
    limitCode[0] = 0x00;
    //AESKey16bytes
    Byte AESKeyBytes[16];
    for (int i = 0; i<16;i++){
        NSString *byteStr = [AESKeyCode substringWithRange:NSMakeRange(i, 1)];
        AESKeyBytes[i] = [byteStr strToByte:byteStr];
    }
    NSData *AESKeyData = [NSData dataWithBytes:AESKeyBytes length:16];
    //钥匙产生的时间6bytes和命令序号2bytes
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYMMddHHmmss"];
    NSString *creattime = [dateformatter stringFromDate:senddate];
    NSLog(@"本机当前时间:%@",creattime);
    NSData *creatData = [creattime convertHexStrToData:creattime];
    NSLog(@"产生时间：%@",creatData);
    //命令序号
    Byte commondNumber[2];
    commondNumber[0] = 0x00;
    commondNumber[1] = 0x00;
    //协议新追加
    [secondData appendBytes:limitCode length:1];
    [secondData appendData:AESKeyData];
    [secondData appendData:creatData];
    [secondData appendData:[NSData dataWithBytes:commondNumber length:2]];
    //=================================================
    
    /***
     命令码 0xc4
     手机号
     起始时间
     终止时间 全是0
     ****/
    
    //命令码
    Byte sendCommand[1];
    sendCommand[0] = 0xc4;
    //起始时间
    NSData *startData = [@"000000000000" convertHexStrToData:@"000000000000"];
    NSLog(@"起始时间：%@",startData);
    //终止时间
    NSData *endtimeData = [@"000000000000" convertHexStrToData:@"000000000000"];
    NSLog(@"结束时间：%@",endtimeData);
    
    NSString *numberStr = [NSString stringWithFormat:@"000000000000"];
    NSLog(@"发送的手机号:%@",numberStr);
    Byte nameUser[12];
    for (int i = 0; i<12;i++ ){
        NSString *byteStr = [numberStr substringWithRange:NSMakeRange(i, 1)];
        nameUser[i] = [byteStr strToByte:byteStr];
    }
    NSData *nameUserData = [NSData dataWithBytes:nameUser length:12];
    
    [secondData appendData:[NSData dataWithBytes:sendCommand length:1]];//命令码
    [secondData appendData:nameUserData];//被授权用户的手机号
    [secondData appendData:startData];
    [secondData appendData:endtimeData];
    
    NSData *RSAData = [RSA_C encryptData:secondData publicKey:rsaPublicKey];
    NSLog(@"RSA加密后的数据长度:%zd",RSAData.length);
    
    return RSAData;
}

#pragma mark - 委托校时
+(void)accreditDoCheckTime:(NSData *)AesKey andPrigher:(CBPeripheral *)peripheral and:(CBCharacteristic *)characteristic withData:(NSData *)RSAData lastAESPackage:(NSData *)lastAESPackage{
    /***
     包头
     数据长度 0xb7
     控制码 0x82
     **/
    NSMutableData *openLockData = [[NSMutableData alloc]init];
    
    Byte ucCommandSend[23];
    
    ucCommandSend[0]= 0xfa;
    ucCommandSend[1]= 0xfb;
    ucCommandSend[2]= 0x00;
    ucCommandSend[3]= 0xe7;
    ucCommandSend[4]= 0x50;
    ucCommandSend[5] = 0x50;
    for (int i = 6; i<22; i++)
    {
        ucCommandSend[i] = 0x00;
    }
    ucCommandSend[22] = 0x82;
    NSData *headData = [NSData dataWithBytes:ucCommandSend length:23];
    [openLockData appendData:headData];
    /********
     *用户名 numberData 12byte
     *本机时间 timeData 6byte YYMMDDHHMMSS
     ********/
    //当前用户绑定手机号
    NSString *nStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"userid"];
    NSString *numberStr = [KLHelp userIDToTwelveByteWithUserID:nStr];
    NSLog(@"发送的手机号:%@",numberStr);
    Byte nameUser[12];
    for (int i = 0; i<12;i++ ){
        NSString *byteStr = [numberStr substringWithRange:NSMakeRange(i, 1)];
        nameUser[i] = [byteStr strToByte:byteStr];
    }
    NSData *nameUserData = [NSData dataWithBytes:nameUser length:12];
    
    //本机当前时间
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYMMddHHmmss"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    NSLog(@"本机当前时间:%@",locationString);
    
    NSData *timeData = [locationString convertHexStrToData:locationString];
    
    NSMutableData *firstData = [[NSMutableData alloc]init];
    [firstData appendData:nameUserData];
    [firstData appendData:timeData];
    
    /**
     拼接18+128
     */
    NSMutableData *mainData = [[NSMutableData alloc]init];
    [mainData appendData:firstData];
    [mainData appendData:RSAData];
    [mainData appendData:lastAESPackage];
    
    //aes
    NSData *aesEncryData = [AES128EBC_No_Padding_Unit AES128Encrypt:mainData withAESKey:AesKey];
    
    [openLockData appendData:aesEncryData];
    
    //cs
    
    NSData *csenddata = [aesEncryData getCheckSum:aesEncryData];
    [openLockData appendData:csenddata];
    //0x16
    Byte endCommand[8];
    endCommand[0] = 0x16;
    endCommand[1] = 0x00;
    endCommand[2] = 0x00;
    endCommand[3] = 0x00;
    endCommand[4] = 0x00;
    endCommand[5] = 0x00;
    endCommand[6] = 0x00;
    endCommand[7] = 0x00;
    
    NSData *endComData = [NSData dataWithBytes:endCommand length:8];
    [openLockData appendData:endComData];
    NSLog(@"openLockData.length = %lu",(unsigned long)openLockData.length);
    
    for (int i = 0; i<openLockData.length/20; i++)
    {
        NSData *sendData = [openLockData subdataWithRange:NSMakeRange(i*20, 20)];
        NSString *responseFlag = [[NSUserDefaults standardUserDefaults] objectForKey:@"responseFlag"];
        if([responseFlag isEqualToString:@"1a"]){
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }else{
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
        }
    }
}

#pragma mark - 锁主设置黑名单
+(void)settingBlackList:(NSData *)AesKey andPrigher:(CBPeripheral *)peripheral and:(CBCharacteristic *)characteristic withRSApublickeKey:(NSString *)rsaPublic blackMobile:(NSString *)mobile{
    /***
     包头
     数据长度 0xb7
     控制码 0x82
     **/
    NSMutableData *openLockData = [[NSMutableData alloc]init];
    
    Byte ucCommandSend[23];
    
    ucCommandSend[0]= 0xfa;
    ucCommandSend[1]= 0xfb;
    
    ucCommandSend[2]= 0x00;
    ucCommandSend[3]= 0xe7;
    
    ucCommandSend[4]= 0x50;
    ucCommandSend[5] = 0x50;
    for (int i = 6; i<22; i++)
    {
        ucCommandSend[i] = 0x00;
    }
    ucCommandSend[22] = 0x82;
    NSData *headData = [NSData dataWithBytes:ucCommandSend length:23];
    [openLockData appendData:headData];
    /*********
     *用户名 numberData 12byte
     *本机时间 timeData 6byte YYMMDDHHMMSS
     ****/
    //当前用户绑定手机号
    NSString *nStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"userid"];
    NSString *numberStr = [KLHelp userIDToTwelveByteWithUserID:nStr];
    Byte nameUser[12];
    for (int i = 0; i<12;i++ ){
        NSString *byteStr = [numberStr substringWithRange:NSMakeRange(i, 1)];
        nameUser[i] = [byteStr strToByte:byteStr];
    }
    NSData *nameUserData = [NSData dataWithBytes:nameUser length:12];
    NSLog(@"发送的手机号:%@",nameUserData);
    
    //本机当前时间
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYMMddHHmmss"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    NSLog(@"本机当前时间:%@",locationString);
    
    NSData *timeData = [locationString convertHexStrToData:locationString];
    
    NSMutableData *firstData = [[NSMutableData alloc]init];
    [firstData appendData:nameUserData];
    [firstData appendData:timeData];
    
    NSMutableData *secondData = [[NSMutableData alloc]init];
    //权限码1bytes
    Byte limitCode[1];
    limitCode[0] = 0x00;
    //AESKey16bytes
    NSString *AESKeyCode = [KLHelp getUserSixTeenRandomAESKey];
    Byte AESKeyBytes[16];
    for (int i = 0; i<16;i++){
        NSString *byteStr = [AESKeyCode substringWithRange:NSMakeRange(i, 1)];
        AESKeyBytes[i] = [byteStr strToByte:byteStr];
    }
    NSData *AESKeyData = [NSData dataWithBytes:AESKeyBytes length:16];
    NSLog(@"limitData:%@",AESKeyData);
    
    /***
     命令码 0xc1
     手机号
     起始时间
     终止时间 全是0
     ****/
    
    //命令码
    Byte sendCommand[1];
    sendCommand[0] = 0xc1;
    //被设置黑名单用户的手机号
    NSString *blackUser = [KLHelp userIDToTwelveByteWithUserID:mobile];
    Byte blackMobile[12];
    for (int i = 0; i<12;i++ ){
        NSString *byteStr = [blackUser substringWithRange:NSMakeRange(i, 1)];
        blackMobile[i] = [byteStr strToByte:byteStr];
    }
    NSData *blackUserData = [NSData dataWithBytes:blackMobile length:12];
    NSLog(@"设置的黑名单用户：%@",blackUserData);
    
    [secondData appendBytes:limitCode length:1];
    [secondData appendData:AESKeyData];
    [secondData appendData:[AESKeyData subdataWithRange:NSMakeRange(0, 8)]];//填充8个字节
    [secondData appendData:[NSData dataWithBytes:sendCommand length:1]];//命令码
    [secondData appendData:nameUserData];//被授权用户的手机号
    [secondData appendData:blackUserData];//被设置黑名单的用户手机号
    
    NSData *RSAData = [RSA_C encryptData:secondData publicKey:rsaPublic];
    NSLog(@"RSA加密后的数据长度:%zd",RSAData.length);
    /******************************************************************************************/
    //锁主自定义AES包
    NSMutableData *newAesSecurit = [[NSMutableData alloc]initWithCapacity:38];
    //添加权限码
    [newAesSecurit appendBytes:limitCode length:1];
    //添加12个字节的设置用户(开锁指令为全0)
    [newAesSecurit appendData:blackUserData];
    //添加命令码
    [newAesSecurit appendData:[NSData dataWithBytes:sendCommand length:1]];
    //添加当前用户
    [newAesSecurit appendData:nameUserData];
    //添加起始时间
    NSData *startData = [@"000000000000" convertHexStrToData:@"000000000000"];
    [newAesSecurit appendData:startData];
    //添加终止时间
    [newAesSecurit appendData:startData];
    //对锁主自定义AES包加密
    NSData *newAesSecuritEncryption = [AES128EBC_No_Padding_Unit AES128Encrypt:newAesSecurit withAESKey:AESKeyData];
    
    /**
     拼接18+128
     */
    NSMutableData *mainData = [[NSMutableData alloc]init];
    [mainData appendData:firstData];
    [mainData appendData:RSAData];
    [mainData appendData:newAesSecuritEncryption];
    
    //aes
    NSData *aesEncryData = [AES128EBC_No_Padding_Unit AES128Encrypt:mainData withAESKey:AesKey];
    NSLog(@"数据主体的长度:%zd",aesEncryData.length);
    
    [openLockData appendData:aesEncryData];
    
    //cs
    NSData *csenddata = [aesEncryData getCheckSum:aesEncryData];
    [openLockData appendData:csenddata];
    
    //0x16
    Byte endCommand[8];
    endCommand[0] = 0x16;
    endCommand[1] = 0x00;
    endCommand[2] = 0x00;
    endCommand[3] = 0x00;
    endCommand[4] = 0x00;
    endCommand[5] = 0x00;
    endCommand[6] = 0x00;
    endCommand[7] = 0x00;
    
    NSData *endComData = [NSData dataWithBytes:endCommand length:8];
    [openLockData appendData:endComData];
    NSLog(@"黑名单设置的数据长度:%lu",(unsigned long)openLockData.length);
    for (int i = 0; i<openLockData.length/20; i++){
        NSData *sendData = [openLockData subdataWithRange:NSMakeRange(i*20, 20)];
        NSString *responseFlag = [[NSUserDefaults standardUserDefaults] objectForKey:@"responseFlag"];
        if([responseFlag isEqualToString:@"1a"]){
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }else{
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
        }
    }
}

#pragma mark - 打包设置黑名单指令包
+(NSData *)packageSettingBlackUserWithPhone:(NSString *)phoneNumber psaPublicKey:(NSString *)rsaPublicKey userAESKey:(NSString *)AESKeyCode{
    NSMutableData *secondData = [[NSMutableData alloc]init];
    //权限码1bytes
    Byte limitCode[1];
    limitCode[0] = 0x00;
    //AESKey16bytes
    Byte AESKeyBytes[16];
    for (int i = 0; i<16;i++){
        NSString *byteStr = [AESKeyCode substringWithRange:NSMakeRange(i, 1)];
        AESKeyBytes[i] = [byteStr strToByte:byteStr];
    }
    NSData *AESKeyData = [NSData dataWithBytes:AESKeyBytes length:16];
    NSLog(@"limitData:%@",AESKeyData);
    /***
     命令码 0xc1
     手机号
     起始时间
     终止时间 全是0
     ****/
    
    //命令码
    Byte sendCommand[1];
    sendCommand[0] = 0xc1;
    //用户手机号
    NSString *userName = [NSString stringWithFormat:@"000000000000"];
    Byte userNameMobile[12];
    for (int i = 0; i<12;i++ ){
        NSString *byteStr = [userName substringWithRange:NSMakeRange(i, 1)];
        userNameMobile[i] = [byteStr strToByte:byteStr];
    }
    NSData *nameUserData = [NSData dataWithBytes:userNameMobile length:12];
    //被设置黑名单用户的手机号
    NSString *blackUser = [NSString stringWithFormat:@"%@0",phoneNumber];
    Byte blackMobile[12];
    for (int i = 0; i<12;i++ ){
        NSString *byteStr = [blackUser substringWithRange:NSMakeRange(i, 1)];
        blackMobile[i] = [byteStr strToByte:byteStr];
    }
    NSData *blackUserData = [NSData dataWithBytes:blackMobile length:12];
    NSLog(@"设置的黑名单用户：%@",blackUserData);
    
    [secondData appendBytes:limitCode length:1];
    [secondData appendData:AESKeyData];
    [secondData appendData:[AESKeyData subdataWithRange:NSMakeRange(0, 8)]];//填充8个字节
    [secondData appendData:[NSData dataWithBytes:sendCommand length:1]];//命令码
    [secondData appendData:nameUserData];//被授权用户的手机号
    [secondData appendData:blackUserData];//被设置黑名单的用户手机号
    
    NSData *RSAData = [RSA_C encryptData:secondData publicKey:rsaPublicKey];
    NSLog(@"RSA加密后的数据长度:%zd",RSAData.length);
    
    return RSAData;
}

#pragma mark - 委托设置黑名单
+(void)accreditDoSettingBlackUser:(NSData *)AesKey andPrigher:(CBPeripheral *)peripheral and:(CBCharacteristic *)characteristic withData:(NSData *)RSAData lastAESPackage:(NSData *)lastAESPackage{
    /***
     包头
     数据长度 0xb7
     控制码 0x82
     **/
    NSMutableData *openLockData = [[NSMutableData alloc]init];
    
    Byte ucCommandSend[23];
    ucCommandSend[0]= 0xfa;
    ucCommandSend[1]= 0xfb;
    ucCommandSend[2]= 0x00;
    ucCommandSend[3]= 0xe7;
    ucCommandSend[4]= 0x50;
    ucCommandSend[5] = 0x50;
    for (int i = 6; i<22; i++)
    {
        ucCommandSend[i] = 0x00;
    }
    ucCommandSend[22] = 0x82;
    NSData *headData = [NSData dataWithBytes:ucCommandSend length:23];
    [openLockData appendData:headData];
    /*********
     *用户名 numberData 12byte
     *本机时间 timeData 6byte YYMMDDHHMMSS
     ****/
    //当前用户绑定手机号
    NSString *nStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"userid"];
    NSString *numberStr = [KLHelp userIDToTwelveByteWithUserID:nStr];
    Byte nameUser[12];
    for (int i = 0; i<12;i++ ){
        NSString *byteStr = [numberStr substringWithRange:NSMakeRange(i, 1)];
        nameUser[i] = [byteStr strToByte:byteStr];
    }
    NSData *nameUserData = [NSData dataWithBytes:nameUser length:12];
    NSLog(@"发送的手机号:%@",nameUserData);
    
    //本机当前时间
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYMMddHHmmss"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    NSLog(@"本机当前时间:%@",locationString);
    
    NSData *timeData = [locationString convertHexStrToData:locationString];
    
    NSMutableData *firstData = [[NSMutableData alloc]init];
    [firstData appendData:nameUserData];
    [firstData appendData:timeData];
    
    /**
     拼接18+128
     */
    NSMutableData *mainData = [[NSMutableData alloc]init];
    [mainData appendData:firstData];
    [mainData appendData:RSAData];
    [mainData appendData:lastAESPackage];
    
    //aes
    NSData *aesEncryData = [AES128EBC_No_Padding_Unit AES128Encrypt:mainData withAESKey:AesKey];
    NSLog(@"数据主体的长度:%zd",aesEncryData.length);
    
    [openLockData appendData:aesEncryData];
    
    //cs
    NSData *csenddata = [aesEncryData getCheckSum:aesEncryData];
    [openLockData appendData:csenddata];
    
    //0x16
    Byte endCommand[8];
    endCommand[0] = 0x16;
    endCommand[1] = 0x00;
    endCommand[2] = 0x00;
    endCommand[3] = 0x00;
    endCommand[4] = 0x00;
    endCommand[5] = 0x00;
    endCommand[6] = 0x00;
    endCommand[7] = 0x00;
    
    NSData *endComData = [NSData dataWithBytes:endCommand length:8];
    [openLockData appendData:endComData];
    NSLog(@"黑名单设置的数据长度:%lu",(unsigned long)openLockData.length);
    for (int i = 0; i<openLockData.length/20; i++){
        NSData *sendData = [openLockData subdataWithRange:NSMakeRange(i*20, 20)];
        NSString *responseFlag = [[NSUserDefaults standardUserDefaults] objectForKey:@"responseFlag"];
        if([responseFlag isEqualToString:@"1a"]){
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }else{
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
        }
    }
}

#pragma mark - 锁主取消黑名单
+(void)cancelBlackList:(NSData *)AesKey andPrigher:(CBPeripheral *)peripheral and:(CBCharacteristic *)characteristic withRSApublickeKey:(NSString *)rsaPublic blackMobile:(NSString *)mobile{
    /***
     包头
     数据长度 0xb7
     控制码 0x82
     **/
    NSMutableData *openLockData = [[NSMutableData alloc]init];
    
    Byte ucCommandSend[23];
    
    ucCommandSend[0]= 0xfa;
    ucCommandSend[1]= 0xfb;
    ucCommandSend[2]= 0x00;
    ucCommandSend[3]= 0xe7;
    ucCommandSend[4]= 0x50;
    ucCommandSend[5] = 0x50;
    for (int i = 6; i<22; i++)
    {
        ucCommandSend[i] = 0x00;
    }
    ucCommandSend[22] = 0x82;
    NSData *headData = [NSData dataWithBytes:ucCommandSend length:23];
    [openLockData appendData:headData];
    /*********
     *用户名 numberData 12byte
     *本机时间 timeData 6byte YYMMDDHHMMSS
     ****/
    //当前用户绑定手机号
    NSString *nStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"userid"];
    NSString *numberStr = [KLHelp userIDToTwelveByteWithUserID:nStr];
    Byte nameUser[12];
    for (int i = 0; i<12;i++ ){
        NSString *byteStr = [numberStr substringWithRange:NSMakeRange(i, 1)];
        nameUser[i] = [byteStr strToByte:byteStr];
    }
    NSData *nameUserData = [NSData dataWithBytes:nameUser length:12];
    NSLog(@"发送的手机号:%@",nameUserData);
    
    //本机当前时间
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYMMddHHmmss"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    NSLog(@"本机当前时间:%@",locationString);
    
    NSData *timeData = [locationString convertHexStrToData:locationString];
    
    NSMutableData *firstData = [[NSMutableData alloc]init];
    [firstData appendData:nameUserData];
    [firstData appendData:timeData];
    
    NSMutableData *secondData = [[NSMutableData alloc]init];
    //权限码1bytes
    Byte limitCode[1];
    limitCode[0] = 0x00;
    //AESKey16bytes
    NSString *AESKeyCode = [KLHelp getUserSixTeenRandomAESKey];
    Byte AESKeyBytes[16];
    for (int i = 0; i<16;i++){
        NSString *byteStr = [AESKeyCode substringWithRange:NSMakeRange(i, 1)];
        AESKeyBytes[i] = [byteStr strToByte:byteStr];
    }
    NSData *AESKeyData = [NSData dataWithBytes:AESKeyBytes length:16];
    NSLog(@"limitData:%@",AESKeyData);
    /***
     命令码 0xc2
     手机号
     起始时间
     终止时间 全是0
     ****/
    
    //命令码
    Byte sendCommand[1];
    sendCommand[0] = 0xc2;
    //被设置黑名单用户的手机号
    NSString *blackUser = [KLHelp userIDToTwelveByteWithUserID:mobile];
    Byte blackMobile[12];
    for (int i = 0; i<12;i++ ){
        NSString *byteStr = [blackUser substringWithRange:NSMakeRange(i, 1)];
        blackMobile[i] = [byteStr strToByte:byteStr];
    }
    NSData *blackUserData = [NSData dataWithBytes:blackMobile length:12];
    NSLog(@"取消的黑名单用户：%@",blackUserData);
    
    [secondData appendBytes:limitCode length:1];
    [secondData appendData:AESKeyData];
    [secondData appendData:[AESKeyData subdataWithRange:NSMakeRange(0, 8)]];//填充8个字节
    [secondData appendData:[NSData dataWithBytes:sendCommand length:1]];//命令码
    [secondData appendData:nameUserData];//被授权用户的手机号
    [secondData appendData:blackUserData];//被取消黑名单的用户手机号
    
    NSData *RSAData = [RSA_C encryptData:secondData publicKey:rsaPublic];
    NSLog(@"RSA加密后的数据长度:%zd",RSAData.length);
    
    /******************************************************************************************/
    //锁主自定义AES包
    NSMutableData *newAesSecurit = [[NSMutableData alloc]initWithCapacity:38];
    //添加权限码
    [newAesSecurit appendBytes:limitCode length:1];
    //添加12个字节的设置用户(开锁指令为全0)
    [newAesSecurit appendData:blackUserData];
    //添加命令码
    [newAesSecurit appendData:[NSData dataWithBytes:sendCommand length:1]];
    //添加当前用户
    [newAesSecurit appendData:nameUserData];
    //添加起始时间
    NSData *startData = [@"000000000000" convertHexStrToData:@"000000000000"];
    [newAesSecurit appendData:startData];
    //添加终止时间
    [newAesSecurit appendData:startData];
    //对锁主自定义AES包加密
    NSData *newAesSecuritEncryption = [AES128EBC_No_Padding_Unit AES128Encrypt:newAesSecurit withAESKey:AESKeyData];
    /**
     拼接18+128
     */
    NSMutableData *mainData = [[NSMutableData alloc]init];
    [mainData appendData:firstData];
    [mainData appendData:RSAData];
    [mainData appendData:newAesSecuritEncryption];
    
    //aes
    NSData *aesEncryData = [AES128EBC_No_Padding_Unit AES128Encrypt:mainData withAESKey:AesKey];
    NSLog(@"数据主体的长度:%zd",aesEncryData.length);
    
    [openLockData appendData:aesEncryData];
    
    //cs
    NSData *csenddata = [aesEncryData getCheckSum:aesEncryData];
    [openLockData appendData:csenddata];
    
    //0x16
    Byte endCommand[8];
    endCommand[0] = 0x16;
    endCommand[1] = 0x00;
    endCommand[2] = 0x00;
    endCommand[3] = 0x00;
    endCommand[4] = 0x00;
    endCommand[5] = 0x00;
    endCommand[6] = 0x00;
    endCommand[7] = 0x00;
    
    NSData *endComData = [NSData dataWithBytes:endCommand length:8];
    [openLockData appendData:endComData];
    NSLog(@"取消黑名单的数据长度:%lu",(unsigned long)openLockData.length);
    for (int i = 0; i<openLockData.length/20; i++){
        NSData *sendData = [openLockData subdataWithRange:NSMakeRange(i*20, 20)];
        NSString *responseFlag = [[NSUserDefaults standardUserDefaults] objectForKey:@"responseFlag"];
        if([responseFlag isEqualToString:@"1a"]){
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }else{
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
        }
    }
}

#pragma mark - 打包取消黑名单指令包
+(NSData *)packageCancelBlackUserWithPhone:(NSString *)phoneNumber psaPublicKey:(NSString *)rsaPublicKey userAESKey:(NSString *)AESKeyCode{
    NSMutableData *secondData = [[NSMutableData alloc]init];
    //权限码1bytes
    Byte limitCode[1];
    limitCode[0] = 0x00;
    //AESKey16bytes
    Byte AESKeyBytes[16];
    for (int i = 0; i<16;i++){
        NSString *byteStr = [AESKeyCode substringWithRange:NSMakeRange(i, 1)];
        AESKeyBytes[i] = [byteStr strToByte:byteStr];
    }
    NSData *AESKeyData = [NSData dataWithBytes:AESKeyBytes length:16];
    NSLog(@"limitData:%@",AESKeyData);
    /***
     命令码 0xc2
     手机号
     起始时间
     终止时间 全是0
     ****/
    
    //命令码
    Byte sendCommand[1];
    sendCommand[0] = 0xc2;
    //用户手机号
    NSString *userName = [NSString stringWithFormat:@"000000000000"];
    Byte userNameMobile[12];
    for (int i = 0; i<12;i++ ){
        NSString *byteStr = [userName substringWithRange:NSMakeRange(i, 1)];
        userNameMobile[i] = [byteStr strToByte:byteStr];
    }
    NSData *nameUserData = [NSData dataWithBytes:userNameMobile length:12];
    //被设置黑名单用户的手机号
    NSString *blackUser = [NSString stringWithFormat:@"%@0",phoneNumber];
    Byte blackMobile[12];
    for (int i = 0; i<12;i++ ){
        NSString *byteStr = [blackUser substringWithRange:NSMakeRange(i, 1)];
        blackMobile[i] = [byteStr strToByte:byteStr];
    }
    NSData *blackUserData = [NSData dataWithBytes:blackMobile length:12];
    NSLog(@"设置的黑名单用户：%@",blackUserData);
    
    [secondData appendBytes:limitCode length:1];
    [secondData appendData:AESKeyData];
    [secondData appendData:[AESKeyData subdataWithRange:NSMakeRange(0, 8)]];//填充8个字节
    [secondData appendData:[NSData dataWithBytes:sendCommand length:1]];//命令码
    [secondData appendData:nameUserData];//被授权用户的手机号
    [secondData appendData:blackUserData];//被设置黑名单的用户手机号
    
    NSData *RSAData = [RSA_C encryptData:secondData publicKey:rsaPublicKey];
    NSLog(@"RSA加密后的数据长度:%zd",RSAData.length);
    
    return RSAData;
}

#pragma mark - 委托取消设置黑名单
+(void)accreditDoCancelBlackUser:(NSData *)AesKey andPrigher:(CBPeripheral *)peripheral and:(CBCharacteristic *)characteristic withData:(NSData *)RSAData lastAESPackage:(NSData *)lastAESPackage{
    /***
     包头
     数据长度 0xb7
     控制码 0x82
     **/
    NSMutableData *openLockData = [[NSMutableData alloc]init];
    
    Byte ucCommandSend[23];
    
    ucCommandSend[0]= 0xfa;
    ucCommandSend[1]= 0xfb;
    ucCommandSend[2]= 0x00;
    ucCommandSend[3]= 0xe7;
    ucCommandSend[4]= 0x50;
    ucCommandSend[5] = 0x50;
    for (int i = 6; i<22; i++)
    {
        ucCommandSend[i] = 0x00;
    }
    ucCommandSend[22] = 0x82;
    NSData *headData = [NSData dataWithBytes:ucCommandSend length:23];
    [openLockData appendData:headData];
    /*********
     *用户名 numberData 12byte
     *本机时间 timeData 6byte YYMMDDHHMMSS
     ****/
    //当前用户绑定手机号
    NSString *nStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"userid"];
    NSString *numberStr = [KLHelp userIDToTwelveByteWithUserID:nStr];
    Byte nameUser[12];
    for (int i = 0; i<12;i++ ){
        NSString *byteStr = [numberStr substringWithRange:NSMakeRange(i, 1)];
        nameUser[i] = [byteStr strToByte:byteStr];
    }
    NSData *nameUserData = [NSData dataWithBytes:nameUser length:12];
    NSLog(@"发送的手机号:%@",nameUserData);
    
    //本机当前时间
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYMMddHHmmss"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    NSLog(@"本机当前时间:%@",locationString);
    
    NSData *timeData = [locationString convertHexStrToData:locationString];
    
    NSMutableData *firstData = [[NSMutableData alloc]init];
    [firstData appendData:nameUserData];
    [firstData appendData:timeData];
    
    /**
     拼接18+128
     */
    NSMutableData *mainData = [[NSMutableData alloc]init];
    [mainData appendData:firstData];
    [mainData appendData:RSAData];
    [mainData appendData:lastAESPackage];
    
    //aes
    NSData *aesEncryData = [AES128EBC_No_Padding_Unit AES128Encrypt:mainData withAESKey:AesKey];
    NSLog(@"数据主体的长度:%zd",aesEncryData.length);
    
    [openLockData appendData:aesEncryData];
    
    //cs
    NSData *csenddata = [aesEncryData getCheckSum:aesEncryData];
    [openLockData appendData:csenddata];
    
    //0x16
    Byte endCommand[8];
    endCommand[0] = 0x16;
    endCommand[1] = 0x00;
    endCommand[2] = 0x00;
    endCommand[3] = 0x00;
    endCommand[4] = 0x00;
    endCommand[5] = 0x00;
    endCommand[6] = 0x00;
    endCommand[7] = 0x00;
    
    NSData *endComData = [NSData dataWithBytes:endCommand length:8];
    [openLockData appendData:endComData];
    NSLog(@"黑名单设置的数据长度:%lu",(unsigned long)openLockData.length);
    for (int i = 0; i<openLockData.length/20; i++){
        NSData *sendData = [openLockData subdataWithRange:NSMakeRange(i*20, 20)];
        NSString *responseFlag = [[NSUserDefaults standardUserDefaults] objectForKey:@"responseFlag"];
        if([responseFlag isEqualToString:@"1a"]){
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }else{
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
        }
    }
}

#pragma mark - publickKey对象转NSData
+ (NSData *)getPublicKeyBitsFromKey:(SecKeyRef)givenKey {
    static const uint8_t publicKeyIdentifier[] = "com.your.company.publickey";
    NSData *publicTag = [[NSData alloc] initWithBytes:publicKeyIdentifier length:sizeof(publicKeyIdentifier)];
    
    OSStatus sanityCheck = noErr;
    NSData * publicKeyBits = nil;
    
    NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init];
    [queryPublicKey setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass];
    [queryPublicKey setObject:publicTag forKey:(__bridge id)kSecAttrApplicationTag];
    [queryPublicKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
    
    // Temporarily add key to the Keychain, return as data:
    NSMutableDictionary * attributes = [queryPublicKey mutableCopy];
    [attributes setObject:(__bridge id)givenKey forKey:(__bridge id)kSecValueRef];
    [attributes setObject:@YES forKey:(__bridge id)kSecReturnData];
    CFTypeRef result;
    sanityCheck = SecItemAdd((__bridge CFDictionaryRef) attributes, &result);
    if (sanityCheck == errSecSuccess) {
        publicKeyBits = CFBridgingRelease(result);
        
        // Remove from Keychain again:
        (void)SecItemDelete((__bridge CFDictionaryRef) queryPublicKey);
    }
    
    return publicKeyBits;
}

#pragma mark - 读取锁内信息
+(void)readLockMessage:(NSData *)AesKey andPrigher:(CBPeripheral *)peripheral and:(CBCharacteristic *)characteristic withRSApublickeKey:(NSString *)rsaPublic{
    /***
     包头
     数据长度 0xb7
     控制码 0x82
     **/
    NSMutableData *openLockData = [[NSMutableData alloc]init];
    
    Byte ucCommandSend[23];
    
    ucCommandSend[0]= 0xfa;
    ucCommandSend[1]= 0xfb;
    ucCommandSend[2]= 0x00;
    ucCommandSend[3]= 0xe7;
    ucCommandSend[4]= 0x50;
    ucCommandSend[5] = 0x50;
    for (int i = 6; i<22; i++)
    {
        ucCommandSend[i] = 0x00;
    }
    ucCommandSend[22] = 0x82;
    NSData *headData = [NSData dataWithBytes:ucCommandSend length:23];
    [openLockData appendData:headData];
    /********
     *用户名 numberData 12byte
     *本机时间 timeData 6byte YYMMDDHHMMSS
     ********/
    //当前用户绑定手机号
    NSString *nStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"userid"];
    NSString *numberStr = [KLHelp userIDToTwelveByteWithUserID:nStr];
    Byte nameUser[12];
    for (int i = 0; i<12;i++ ){
        NSString *byteStr = [numberStr substringWithRange:NSMakeRange(i, 1)];
        nameUser[i] = [byteStr strToByte:byteStr];
    }
    NSData *nameUserData = [NSData dataWithBytes:nameUser length:12];
    NSLog(@"发送的手机号:%@",numberStr);
    
    //本机当前时间
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYMMddHHmmss"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    NSLog(@"本机当前时间:%@",locationString);
    
    NSData *timeData = [locationString convertHexStrToData:locationString];
    
    NSMutableData *firstData = [[NSMutableData alloc]init];
    [firstData appendData:nameUserData];
    [firstData appendData:timeData];
    
    /***
     命令码 0XC3
     手机号
     起始时间
     ****/
    
    NSMutableData *secondData = [[NSMutableData alloc]init];
    //权限码1bytes
    Byte limitCode[1];
    limitCode[0] = 0x00;
    //AESKey16bytes
    NSString *AESKeyCode = [KLHelp getUserSixTeenRandomAESKey];
    Byte AESKeyBytes[16];
    for (int i = 0; i<16;i++){
        NSString *byteStr = [AESKeyCode substringWithRange:NSMakeRange(i, 1)];
        AESKeyBytes[i] = [byteStr strToByte:byteStr];
    }
    NSData *AESKeyData = [NSData dataWithBytes:AESKeyBytes length:16];
    NSLog(@"limitData:%@",AESKeyData);
    //命令码
    Byte sendCommand[1];
    sendCommand[0] = 0xc3;
    //起始时间
    NSString *starttime = @"000000000000";
    NSData *startData = [starttime convertHexStrToData:starttime];
    //终止时间
    NSString *endtimeStr =@"000000000000";
    NSData *endtimeData = [endtimeStr convertHexStrToData:endtimeStr];
    NSLog(@"结束时间：%@",endtimeData);
    
    [secondData appendBytes:limitCode length:1];
    [secondData appendData:AESKeyData];
    [secondData appendData:[AESKeyData subdataWithRange:NSMakeRange(0, 8)]];//填充8个字节
    [secondData appendData:[NSData dataWithBytes:sendCommand length:1]];//命令码
    [secondData appendData:nameUserData];//被授权用户的手机号
    [secondData appendData:startData];
    [secondData appendData:endtimeData];
    
    
    NSData *RSAData = [RSA_C encryptData:secondData publicKey:rsaPublic];
    NSLog(@"RSA加密后的数据长度:%zd",RSAData.length);
    
    /******************************************************************************************/
    //锁主自定义AES包
    NSMutableData *newAesSecurit = [[NSMutableData alloc]initWithCapacity:38];
    //添加权限码
    [newAesSecurit appendBytes:limitCode length:1];
    //添加12个字节的设置用户(开锁指令为全0)
    [newAesSecurit appendData:startData];
    [newAesSecurit appendData:startData];
    //添加命令码
    [newAesSecurit appendData:[NSData dataWithBytes:sendCommand length:1]];
    //添加当前用户
    [newAesSecurit appendData:nameUserData];
    //添加起始时间
    [newAesSecurit appendData:startData];
    //添加终止时间
    [newAesSecurit appendData:startData];
    //对锁主自定义AES包加密
    NSData *newAesSecuritEncryption = [AES128EBC_No_Padding_Unit AES128Encrypt:newAesSecurit withAESKey:AESKeyData];
    
    /**
     拼接18+128
     */
    NSMutableData *mainData = [[NSMutableData alloc]init];
    [mainData appendData:firstData];
    [mainData appendData:RSAData];
    [mainData appendData:newAesSecuritEncryption];
    
    NSLog(@"mainData:%@",mainData);
    
    //aes
    NSData *aesEncryData = [AES128EBC_No_Padding_Unit AES128Encrypt:mainData withAESKey:AesKey];
    NSLog(@"数据主体的长度:%zd",aesEncryData.length);
    
    [openLockData appendData:aesEncryData];
    
    //cs
    NSData *csenddata = [aesEncryData getCheckSum:aesEncryData];
    [openLockData appendData:csenddata];
    
    //0x16
    Byte endCommand[8];
    endCommand[0] = 0x16;
    endCommand[1] = 0x00;
    endCommand[2] = 0x00;
    endCommand[3] = 0x00;
    endCommand[4] = 0x00;
    endCommand[5] = 0x00;
    endCommand[6] = 0x00;
    endCommand[7] = 0x00;
    
    NSData *endComData = [NSData dataWithBytes:endCommand length:8];
    [openLockData appendData:endComData];
    NSLog(@"读锁信息数据长度:%lu",(unsigned long)openLockData.length);
    for (int i = 0; i<openLockData.length/20; i++){
        NSData *sendData = [openLockData subdataWithRange:NSMakeRange(i*20, 20)];
        NSString *responseFlag = [[NSUserDefaults standardUserDefaults] objectForKey:@"responseFlag"];
        if([responseFlag isEqualToString:@"1a"]){
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }else{
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
        }
    }
}


#pragma mark - 换锁芯
+ (void)changeLockCore:(NSData *)AesKey andPeripheral:(CBPeripheral *)peripheral andCharacteristic:(CBCharacteristic *)characteristic andRSAPublicKey:(NSString *)rsaPublicKey {
    NSMutableData *changeLockData = [NSMutableData data];
    
    
    // 一:数据头
    Byte commandHead[23];
    commandHead[0] = 0xfa;
    commandHead[1] = 0xfb;
    
    commandHead[2] = 0x1;
    commandHead[3] = 0xb7; // 数据长度 0x1b7 = 439  数据长度：两个字节，除包头以外所有数据的长度（包含自身）（21+160(AES加密后是16的倍数)+256+1+1）
    
    commandHead[4] = 0x50;
    commandHead[5] = 0x50;
    for (NSInteger i = 6; i < 22; i++) {
        commandHead[i] = 0x00;
    }
    commandHead[22] = 0x85;
    NSData *headerData = [NSData dataWithBytes:commandHead length:23];
    NSLog(@"数据头:%@ 长度:%ld",headerData,(long)headerData.length);
    
    
    // 二:数据主体
    // 用户名+本机时间
    NSMutableData *firstData = [NSMutableData data];
    
    NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"userid"];
    NSString *numberStr = [KLHelp userIDToTwelveByteWithUserID:userName];
    Byte nameUser[12];
    for (int i = 0; i < 12; i++) {
        NSString *byteStr = [numberStr substringWithRange:NSMakeRange(i, 1)];
        nameUser[i] = [byteStr strToByte:byteStr];
    }
    NSData *nameUserData = [NSData dataWithBytes:nameUser length:12];
    NSLog(@"用户名%@ 长度:%ld",nameUserData,(long)nameUserData.length);
    
    //本机当前时间
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYMMddHHmmss"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    NSLog(@"本机当前时间:%@",locationString);
    NSData *timeData = [locationString convertHexStrToData:locationString];
    [firstData appendData:nameUserData];
    [firstData appendData:timeData];
    NSLog(@"用户名+当前时间:%@ 长度:%ld",firstData,(long)firstData.length);
    
    // RSA 数据部分
    NSMutableData *rsaData = [NSMutableData data];
    
    NSArray *privateKeyParaArr = [self getPrivateParameterWithPrivateKey:[self getGTMBase64DecodePrivateKeyAndPublicKey:^(NSString *pKey) {
        
        // 坑点:去掉换行符，否则会导致公钥不对，无法开锁
        pKey = [pKey stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
        
        //获取锁公钥
        NSString *jsonStr = [SSKeychain passwordForService:@"com.kisslock.guoyang" account:@"publickeysdic"];
        NSDictionary *publicKeysDic = [KLHelp dictionaryWithJsonString:jsonStr];
        NSMutableDictionary *mutablePublicKeysDic = [NSMutableDictionary dictionaryWithDictionary:publicKeysDic];
        
        [mutablePublicKeysDic setObject:pKey forKey:peripheral.name];
        NSLog(@"------%@--------%@",pKey,peripheral.name);
        NSLog(@"=======%@",publicKeysDic);
        
        [SSKeychain setPassword:[KLHelp dictionaryToJson:mutablePublicKeysDic] forService:@"com.kisslock.guoyang"  account:@"publickeysdic"];
        
    }]];
    
    // 私钥参数
    NSMutableData *pdata = [NSMutableData data];
    NSMutableData *qepeqcfData = [NSMutableData data];
    if (privateKeyParaArr.count == 5) {
        pdata = privateKeyParaArr[0];
        NSData *qD = privateKeyParaArr[1];
        NSData *epD = privateKeyParaArr[2];
        NSData *eqD = privateKeyParaArr[3];
        NSData *cfD = privateKeyParaArr[4];
        [qepeqcfData appendData:qD];
        [qepeqcfData appendData:epD];
        [qepeqcfData appendData:eqD];
        [qepeqcfData appendData:cfD];
    }
    NSLog(@"私钥参数p:%@,长度:%ld qepeqcf:%@ 长度:%ld",pdata,(long)pdata.length,qepeqcfData,(long)qepeqcfData.length);
    
    // 蓝牙锁名
    NSString *peripheralName = peripheral.name;
    NSRange range = [peripheralName rangeOfString:@"KissLock"];
      NSString *subStr = [peripheralName substringFromIndex:range.length];
//    NSString *subStr = @"00000000";
    NSData *lockNameData = [subStr convertHexStrToData:subStr];
    NSLog(@"蓝牙锁名:%@",lockNameData);
    
    // 钥匙产生时间 ??? 和 本机时间一样不?
    
    
    //命令序号2bytes
    Byte commondNumber[2];
    commondNumber[0] = 0x00;
    commondNumber[1] = 0x00;
    NSData *commandNumData = [NSData dataWithBytes:commondNumber length:2];
    
    // 命令码
    Byte cmdcode[1];
    cmdcode[0] = 0xa2;
    NSData *cmdcodeData = [NSData dataWithBytes:cmdcode length:1];
    
    // 授权用户名
    
    // 起始时间 终止时间(全0)
    //起始时间
    NSString *starttime = @"000000000000";
    NSData *startData = [starttime convertHexStrToData:starttime];
    NSLog(@"钥匙起始时间：%@",startData);
    //终止时间
    NSString *endtimeStr =@"000000000000";
    NSData *endtimeData = [endtimeStr convertHexStrToData:endtimeStr];
    NSLog(@"钥匙结束时间：%@",endtimeData);
    
    // 拼接中间的rsa 数据，并进行rsa数据加密
    [rsaData appendData:pdata];
    [rsaData appendData:lockNameData];
    [rsaData appendData:timeData];
    [rsaData appendData:commandNumData];
    [rsaData appendData:cmdcodeData];
    [rsaData appendData:nameUserData];
    [rsaData appendData:startData];
    [rsaData appendData:endtimeData];
    NSLog(@"rsa数据:%@ 长度:%ld",rsaData,(long)rsaData.length);
    // 加密
    NSData *rsaEncryptData = [RSA_C encryptData:rsaData publicKey:rsaPublicKey];
    NSLog(@"rsa加密数据:%@ 长度:%ld",rsaEncryptData,(unsigned long)rsaEncryptData.length);
    
    // 对前两段数据进行aeskey 加密
    NSMutableData *mainData = [NSMutableData data];
    [mainData appendData:firstData];
    [mainData appendData:rsaEncryptData];
    NSData *aesEncryptData = [AES128EBC_No_Padding_Unit AES128Encrypt:mainData withAESKey:AesKey];
    NSLog(@"跟换锁芯数据主体:%@ 长度:%ld",aesEncryptData,(unsigned long)aesEncryptData.length);
    
    // cs
    NSMutableData *jiaoyanheData = [NSMutableData data];
//    [jiaoyanheData appendData:headerData];
    [jiaoyanheData appendData:aesEncryptData];
    [jiaoyanheData appendData:qepeqcfData];
    NSString *csLength = [NSString ToHex:(long long int)jiaoyanheData.length];
    csLength = [csLength substringFromIndex:1];
//    NSData *csLengthData = [csLength convertHexStrToData:csLength];
    NSData *csData = [jiaoyanheData getCheckSum:jiaoyanheData];
    NSLog(@"跟换锁芯cs校验和:%@ 长度%@",jiaoyanheData,csData);
    
    // 注:关于结尾补多少个0x00？用代码表示如下
    // （23 + AES加密数据长度（16 的倍数）+ 256 + 1 + n）% 20 = 0;
    //n 就是这个数组元素个数 endCommand[n];
    // 结束符0x16
    Byte endCommand[20];
    endCommand[0] = 0x16;
    endCommand[1] = 0x00;
    endCommand[2] = 0x00;
    endCommand[3] = 0x00;
    endCommand[4] = 0x00;
    endCommand[5] = 0x00;
    endCommand[6] = 0x00;
    endCommand[7] = 0x00;
    endCommand[8] = 0x00;
    endCommand[9] = 0x00;
    endCommand[10] = 0x00;
    endCommand[11] = 0x00;
    endCommand[12] = 0x00;
    endCommand[13] = 0x00;
    endCommand[14] = 0x00;
    endCommand[15] = 0x00;
    endCommand[16] = 0x00;
    endCommand[17] = 0x00;
    endCommand[18] = 0x00;
    endCommand[19] = 0x00;
    
    // 拼接所有数据
    [changeLockData appendData:headerData];    // 数据头
    [changeLockData appendData:aesEncryptData];// aes加密后数据
    [changeLockData appendData:qepeqcfData];   // 私钥参数qepeqcf
    [changeLockData appendData:csData];        // cs
    [changeLockData appendData:[NSData dataWithBytes:endCommand length:20]];                 // 结束符0x16
    NSLog(@"更换锁芯打包后的数据:%@ 长度:%lu",changeLockData,(long)changeLockData.length);
    
    // 发包:
    for (int i = 0 ; i < changeLockData.length /
          20; i++) {
        NSData *sendData = [changeLockData subdataWithRange:NSMakeRange(i * 20, 20)];
        NSString *responseFlag = [[NSUserDefaults standardUserDefaults] objectForKey:@"responseFlag"];
        // 1a 表示有应答的
        if ([responseFlag isEqualToString:@"1a"]) {
            NSLog(@"***********%d",i);
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }else {
            NSLog(@"===========%d",i);
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
        }
    }
}



// 1.获取私钥并进行base64解码 同时通过block把公钥传出去
+ (NSData *)getGTMBase64DecodePrivateKeyAndPublicKey:(void(^)(NSString *pKey))publickBlock{
    BBRSACryptor *rsaCryptor = [[BBRSACryptor alloc] init];
    [rsaCryptor generateRSAKeyPairWithKeySize:1024];
    
    // 获取私钥text
    NSString *privateKey = [rsaCryptor PEMFormatPrivateKey];
    NSString *publicKey= [rsaCryptor PEMFormatPublicKey];
    
    // 防止有时候取出的公钥为空，保存公钥时崩溃
    while (1) {
        if(privateKey == nil || publicKey == nil){
            privateKey = [rsaCryptor PEMFormatPrivateKey];
            publicKey = [rsaCryptor PEMFormatPublicKey];
        }else{
            break;
        }
    }
    
    // 去掉私钥多余字符串
    NSRange spos = [privateKey rangeOfString:@"-----BEGIN RSA PRIVATE KEY-----"];
    NSRange epos = [privateKey rangeOfString:@"-----END RSA PRIVATE KEY-----"];
    if ((spos.location != NSNotFound) && (epos.location != NSNotFound)) {
        NSUInteger s = spos.location + spos.length ; // 起点
        NSUInteger e = epos.location;
        NSRange range = NSMakeRange(s, e-s);
        privateKey = [privateKey substringWithRange:range]; // 截取后重新赋值
    }
    NSLog(@"1.私钥:%@ 长度:%lu",privateKey,(unsigned long)privateKey.length);
    
    // 公钥text
    NSLog(@"______________%@",publicKey);
    // 去掉公钥多余字符串
    NSRange publicBeginRange = [publicKey rangeOfString:@"-----BEGIN PUBLIC KEY-----"];
    NSRange publicEndRange = [publicKey rangeOfString:@"-----END PUBLIC KEY-----"];
    if ((publicBeginRange.location != NSNotFound) && (publicEndRange.location != NSNotFound)) {
        NSUInteger s = publicBeginRange.location + publicBeginRange.length;
        NSUInteger e = publicEndRange.location;
        NSRange range = NSMakeRange(s, e-s);
        publicKey = [publicKey substringWithRange:range]; // 截取后重新覆盖
    }
    NSLog(@"2.公钥:%@ 长度:%zd",publicKey,publicKey.length);
    // 使用blcok 把公钥传出去
    publickBlock(publicKey);
    
    // 对私钥base64解码
    NSData *decodedPrivateData = [GTMBase64 decodeString:privateKey];
    
    // 有时候私钥是空的,防止为空
    if(decodedPrivateData.length == 0){
        [BuleFuction getGTMBase64DecodePrivateKeyAndPublicKey:^(NSString *pKey) {
            //
        }];
    }

    return decodedPrivateData;
}

// 3. 获取私钥参数:对解码后的私钥转为NSString按照0240/0241切割，
// 去掉数组第一个元素,去掉00，再转为data ,放到数组中返回
+ (NSArray *)getPrivateParameterWithPrivateKey:(NSData *)privatekeyData {
    NSMutableArray *resultArr = [NSMutableArray array];
    
    // 3.1 data --》string
    NSString *originStr = [privatekeyData convertDataToHexStr:privatekeyData];
    
    //3.2 切割 0240 / 0241
    //说明:因为RSA .pem 格式的私钥base64解码后的结构是:xxxx0241xxxx2040xxx0241xxx,前后不可能产生空元素，所以这里没做空判断
    // rsa 私钥  参数格式参考
    // http://www.cnblogs.com/jukan/p/5527922.html
    NSArray *firstArray = [originStr componentsSeparatedByString:@"0240"];
    for (NSInteger i = 0; i < firstArray.count; i++) {
        NSString *firstStr = [firstArray objectAtIndex:i];
        
        NSArray *secondArray = [firstStr componentsSeparatedByString:@"0241"];
        
        for (NSInteger j =0; j < secondArray.count; j++) {
            NSString *secondStr = [secondArray objectAtIndex:j];
            NSLog(@"-----去掉0240/0241 后的字符串 %ld %@,   长度:%zd",(long)(i +j),secondStr,secondStr.length/2);
            [resultArr addObject:secondStr];
        }
    }
    
    //3.3 去掉数组中第一个元素:只用到私钥参数的p/q/eq/eq/cf,其他没用
    if (resultArr.count) { // 数组非空
        [resultArr removeObjectAtIndex:0];
    }
    
    // 缓冲一下
    NSArray *tempArr = [NSArray arrayWithArray:resultArr];
    
    //3.4 去掉字符串中的00
    NSMutableArray *newArr = [NSMutableArray array];
    for (NSString *str  in tempArr) {
        // 前两个数是00 扔掉,放入数组中
        if ([[str substringToIndex:2] isEqualToString:@"00"]) {
            NSString *without00Str = [str substringFromIndex:2]; // 去掉00
            [newArr addObject:without00Str];
        }else {
            //没有00 直接放入数组中
            [newArr addObject:str];
        }
    }
    
    NSLog(@"-----%@",newArr);
    
    // 3.5 遍历数组,NSString--》data
    NSMutableArray *without00DataArr = [NSMutableArray array];
    for (NSString *without00Str in newArr) {
        NSLog(@"私钥参数:%@  长度:%zd",without00Str,(long)without00Str.length);
        [without00DataArr addObject:[without00Str convertHexStrToData:without00Str]];
    }
    
    NSLog(@"5个私钥参数:%@",without00DataArr);
    
    return without00DataArr;
}

#pragma mark 5-3 设置密码
+(void)settingPassword:(NSData *)AesKey andPeripheral:(CBPeripheral *)peripheral and:(CBCharacteristic *)characteristic withRSApublickeKey:(NSString *)rsaPublic password:(NSString *)pwd{
    
    NSMutableData *openLockData = [NSMutableData data];
    
    // 一：数据头部23bytes
    Byte cmdSend[23];
    cmdSend[0] = 0xfa;
    cmdSend[1] = 0xfb;
    
    cmdSend[2] = 0x00;
    cmdSend[3] = 0xe7; //数据长度 21 + {[(18+128 + 48（38 AES加密后变为48）)] 208 （192 AES加密后为208）} + 2 = 231 = 0xe7
    
    cmdSend[4] = 0x50;
    cmdSend[5] = 0x50;
    
    for (int i = 6 ; i <=21; i++) {
        cmdSend[i] = 0x00;
    }
    cmdSend[22] = 0x86; // 开锁密码 控制码，
    NSData *headData = [NSData dataWithBytes:cmdSend length:23];
    [openLockData appendData:headData];
    
    
    // 二：数据主体部分
    // 【（当前用户+本机时间）+ RSA加密数据+ （AES部分 新协议）】总体进行AES加密
    // 第一部分数据
    NSData *userNameData = [self userNameData]; // 12bytes
    NSLog(@"发送的手机号:%@ 长度：%zd",userNameData,userNameData.length);
    NSData *currentTimeData = [self currentData]; // 6bytes
    NSLog(@"本机当前时间:%@ 长度：%zd",currentTimeData,currentTimeData.length);
    NSMutableData *firstData = [[NSMutableData alloc] init];
    [firstData appendData:userNameData];
    [firstData appendData:currentTimeData];
    
    // 第二部分数据
    //1.权限码 1bytes
    Byte limitCode[1];
    limitCode[0] = 0x00;
    NSData *limitData = [NSData dataWithBytes:limitCode length:1];
    
    //2.AESKeyCode 用于给第三部分数据加密 16bytes
    NSString *AESKeyCode = [KLHelp getUserSixTeenRandomAESKey];
    Byte AESKeyBytes[16];
    for (int i = 0; i < 16; i++) {
        NSString *byteStr = [AESKeyCode substringWithRange:NSMakeRange(i, 1)];
        AESKeyBytes[i] = [byteStr strToByte:byteStr];
    }
    NSData *AESKeyData = [NSData dataWithBytes:AESKeyBytes length:16];
    NSLog(@"AESKeydata:%@ 长度:%zd",AESKeyData,AESKeyData.length);
    
    //3.指令产生时间+命令序号：随便填 8bytes
    NSData *timeAndcmdnumData = [AESKeyData subdataWithRange:NSMakeRange(0, 8)];
    
    //4.命令码 1byte 0xa3 设置密码
    Byte cmdCode[1];
    cmdCode[0] = 0xa3;
    NSData *cmdCodeData = [NSData dataWithBytes:cmdCode length:1];
    
    //5.授权用户，跟前面的重复了 12bytes
    
    //6.起始时间+终止时间 12bytes 随便填
    NSMutableData *startAndEndTimeData = [NSMutableData data];
    Byte startAndEndByte[12];
    for (int i = 0; i < 12; i++) {
        startAndEndByte[i] = 0x00;
    }
    startAndEndTimeData = [NSMutableData dataWithBytes:startAndEndByte length:12];
    
    NSMutableData *secondData = [[NSMutableData alloc] init];
    [secondData appendData:limitData];
    [secondData appendData:AESKeyData];
    [secondData appendData:timeAndcmdnumData];
    [secondData appendData:cmdCodeData];
    [secondData appendData:userNameData];
    [secondData appendData:startAndEndTimeData]; // 12字节，全0
    
    // 对secondData进行rsa加密
    NSData *RSAData = [RSA_C encryptData:secondData publicKey:rsaPublic];
    NSLog(@"RSAData:%@ 长度:%zd",RSAData,RSAData.length);
    
    
    // 第三部分数据 新协议增加的AES 数据
    // 1.权限码 同上 1byte
    // 2.设置用户 这里填开锁密码 后填充 (6字节+后填充6字节)
    NSData *unlockingData = [self unlockDataWithPwd:pwd];
    NSLog(@"开锁密码数据:%@ 长度:%zd",unlockingData,unlockingData.length);
    
    // 3.命令码 同上 1byte
    // 4.当前用户 同上 12bytes
    // 5.起始时间+终止时间 同上 12bytes
    NSMutableData *thirdData = [[NSMutableData alloc] initWithCapacity:28];
    [thirdData appendData:limitData];     // 1
    [thirdData appendData:unlockingData]; // 12
    [thirdData appendData:cmdCodeData];   // 1
    [thirdData appendData:userNameData];  // 12
    [thirdData appendData:startAndEndTimeData];// 12
    // 最后一部分aes加密数据包
    NSData *lastAESEncryptData = [AES128EBC_No_Padding_Unit AES128Encrypt:thirdData withAESKey:AESKeyData];
    NSLog(@"最后一部分AES加密数据:%@ 长度:%zd",lastAESEncryptData,lastAESEncryptData.length);
    
    
    // 对上述三段数据进行AES加密 18+128+38
    NSMutableData *mainData = [NSMutableData data];
    [mainData appendData:firstData];
    [mainData appendData:RSAData];
    [mainData appendData:lastAESEncryptData];
    NSData *aesEncryptData = [AES128EBC_No_Padding_Unit AES128Encrypt:mainData withAESKey:AesKey];
    NSLog(@"AES加密数据:%@ 长度:%zd",aesEncryptData,aesEncryptData.length);
    
    //三: cs + 结束符
    NSData *csenddata = [aesEncryptData getCheckSum:aesEncryptData];
    
    //0x16
    Byte endCommand[8];
    endCommand[0] = 0x16;
    endCommand[1] = 0x00;
    endCommand[2] = 0x00;
    endCommand[3] = 0x00;
    endCommand[4] = 0x00;
    endCommand[5] = 0x00;
    endCommand[6] = 0x00;
    endCommand[7] = 0x00;
    
    NSData *endData = [NSData dataWithBytes:endCommand length:8];
    
    // 发包
    [openLockData appendData:aesEncryptData];
    [openLockData appendData:csenddata];
    [openLockData appendData:endData];
    NSLog(@"设置开锁密码所有数据:%@ 长度:%zd",openLockData,openLockData.length);

    for (int i = 0; i < openLockData.length / 20; i++) {
        NSData *sendData = [openLockData subdataWithRange:NSMakeRange(i*20, 20)];
        NSString *responseFlag = [[NSUserDefaults standardUserDefaults] objectForKey:@"responseFlag"];
        
        if ([responseFlag isEqualToString:@"1a"]) {
            NSLog(@"*****开锁密码***********%d",i);
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }else {
            NSLog(@"+++++开锁密码+++++++++%d",i);
            [peripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
        }
    }
}

/**当前用户*/
+ (NSData *)userNameData {
    NSString *nStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"userid"];
    NSString *numberStr = [KLHelp userIDToTwelveByteWithUserID:nStr];
    Byte nameUser[12];
    for (int i = 0; i<12;i++ ){
        NSString *byteStr = [numberStr substringWithRange:NSMakeRange(i, 1)];
        nameUser[i] = [byteStr strToByte:byteStr];
    }
    NSData *nameUserData = [NSData dataWithBytes:nameUser length:12];
    
    return nameUserData;
}

/**本机当前时间*/
+ (NSData *)currentData {
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYMMddHHmmss"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    NSData *timeData = [locationString convertHexStrToData:locationString];

    return timeData;
}

/**开锁密码data, 6bytes --> 12bytes*/
// <01020304 05060000 00000000>
+ (NSData *)unlockDataWithPwd:(NSString *)password {
    NSMutableData *passwordData = [NSMutableData dataWithCapacity:12];
    
    //1. 切割密码字符串(6个字节)转为byte
    if (password.length != 6) {
        NSLog(@"开锁密码长度不对!");
        return nil;
    }
    
    Byte firstByte[6];
    for (int i = 0; i < 6; i++) {
        NSString *byteStr = [password substringWithRange:NSMakeRange(i,1)];
        firstByte[i] = [byteStr strToByte:byteStr]; // 一个字符转为一个byte
    }
    NSData *firstData = [NSData dataWithBytes:firstByte length:6];
    
    //2. 后填充6个字节
    Byte behindbyte[6];
    for (int i = 0; i < 6; i++) {
        behindbyte[i] = 0x00;
    }
    NSData *behindData = [NSData dataWithBytes:behindbyte length:6];

    [passwordData appendData:firstData];
    [passwordData appendData:behindData];
    
    return passwordData;
}

#pragma mark 5-11 开锁密码 工具方法
/**6位[0--10]的随机数*/
+ (NSString *)sixRandomStr{
    NSMutableString *ranStr = [NSMutableString string];
    for (int i =0 ; i < 6; i++) {
        int x = arc4random() % 10;
        [ranStr appendString:[NSString stringWithFormat:@"%d",x]];
    }
    NSLog(@"%@",ranStr);
    return ranStr;
}

/**12字节随机开锁密码:前六字节开锁密码，后六字节后填充0*/
+ (NSData *)twelveUnlockpwdWithSixRandomStr:(NSString *)sixRanStr {
    NSMutableData *unlockpwdData = [NSMutableData data];
    
    // 六位数密码转六字节data
    Byte firstByte[6];
    for (int i =0; i < 6; i++) {
        NSString *byteStr = [sixRanStr substringWithRange:NSMakeRange(i, 1)];
        firstByte[i] = [byteStr strToByte:byteStr]; // 字符串转byte
    }
    NSData *firstData = [NSData dataWithBytes:firstByte length:6];
    
    // 后填充6bytes 0
    Byte secondByte[6];
    for (int i = 0; i < 6; i++) {
        secondByte[i] = 0x00;
    }
    NSData *seconData = [NSData dataWithBytes:secondByte length:6];
    
    [unlockpwdData appendData:firstData];
    [unlockpwdData appendData:seconData];
    NSLog(@"随机开锁密码:%@ 长度:%zd",unlockpwdData,unlockpwdData.length);
    return unlockpwdData;
}

@end
